﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HYBYSoft.Company.Models;
using HYBYSoft.Company.WebSite.Helper;

namespace HYBYSoft.Company.WebSite.Areas.Admin.Controllers
{
    public class MemberController : Controller
    {
        /// <summary>
        /// 数据库实体上下文对象
        /// </summary>
        CompanySiteEntities _dbContext = new CompanySiteEntities();

        /// <summary>
        /// 成员管理首页
        /// </summary>
        /// <returns></returns>
        [Authentication]
        public ActionResult Index(string memberName, DateTime? startTime, DateTime? endTime)
        {
            //如果存在提示信息则获取并显示在页面
            if (TempData["PageMessage"] != null)
                ViewBag.Message = TempData["PageMessage"];

            //获得查询条件
            DateTime start = startTime.HasValue ? startTime.Value : DateTime.MinValue;
            DateTime end = endTime.HasValue ? endTime.Value : DateTime.MaxValue;
            string name = memberName ?? string.Empty;

            //根据条件查询用户信息
            var members = from m in _dbContext.Admins
                          where m.State != 0 && m.Name.Contains(name) && (m.CreateTime >= start && m.CreateTime <= end)
                          orderby m.CreateTime descending
                          select m;

            return View(members);
        }

        /// <summary>
        /// 成员查看
        /// </summary>
        /// <param name="member">成员对象实体</param>
        /// <returns></returns>
        [Authentication]
        public ActionResult Details(int id, string pageId)
        {
            ViewBag.PageId = pageId;

            var member = _dbContext.Admins.FirstOrDefault(m => m.AdminID == id);

            return View(member);
        }

        /// <summary>
        /// 根据条件查询成员信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Search()
        {
            return RedirectToAction("Index", new { memberName = Request["MemberName"], startTime = Request["startTime"], endTime = Request["endTime"] });
        }

        /// <summary>
        /// 创建成员页面Get请求
        /// </summary>
        /// <returns></returns>
        [Authentication]
        public ActionResult Create(string pageId)
        {
            ViewBag.PageId = pageId;

            return View();
        }

        /// <summary>
        /// 创建成员
        /// </summary>
        /// <param name="member">成员对象</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Create(HYBYSoft.Company.Models.Admin member)
        {
            if (!this.ModelState.IsValid)
            { return View(); }

            //获得当前用户信息
            CurrentUserInfo user = SecurityHelper.GetCurrentUserInfo();

            //设置新增用户的默认值
            member.Password = SecurityHelper.CreateHashAndBase64(member.Password);
            member.CompanyID = user.CompanyId;
            member.Creator = member.Editor = user.Name;
            member.CreateTime = member.LastEditTime = DateTime.Now;
            member.State = 1;

            //新增账户信息
            _dbContext.AddToAdmins(member);
            _dbContext.SaveChanges();

            return RedirectToAction("Index");
        }

        /// <summary>
        /// 检查用户名是否存在
        /// </summary>
        /// <param name="name">用户名</param>
        /// <returns></returns>
        public ActionResult CheckName(string name)
        {
            var count = (from m in _dbContext.Admins
                         where m.Name == name && m.State != 0
                         select m).Count();

            return Json(count == 0, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 编辑成员界面Get请求
        /// </summary>
        /// <param name="id">成员对象编号</param>
        /// <returns></returns>
        [Authentication]
        public ActionResult Edit(int id, string pageId)
        {
            ViewBag.PageId = pageId;

            var member = _dbContext.Admins.FirstOrDefault(m => m.AdminID == id);

            //将用户密码存储至旧密码字段，并清空现有密码            
            member.Password = string.Empty;
            member.RePassword = string.Empty;

            return View(member);
        }

        /// <summary>
        /// 编辑成员
        /// </summary>
        /// <param name="member">成员对象</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(HYBYSoft.Company.Models.Admin member)
        {
            if (!ModelState.IsValid)
                return View(member);

            //查询原始用户信息
            var originalMember = _dbContext.Admins.FirstOrDefault(m => m.AdminID == member.AdminID);

            //将用户输入的密码加密
            var oldPassword = SecurityHelper.CreateHashAndBase64(member.OldPassword);

            //将加密后的密码与原始密码比较
            if (oldPassword != originalMember.Password)
            {
                ViewBag.Message = "旧密码与原始密码不一致，请重新输入";
                return View(member);
            }

            //获得当前用户信息
            CurrentUserInfo user = SecurityHelper.GetCurrentUserInfo();

            //设置新增用户的默认值
            originalMember.Password = SecurityHelper.CreateHashAndBase64(member.Password);
            originalMember.Editor = user.Name;
            originalMember.LastEditTime = DateTime.Now;

            //修改账户信息
            _dbContext.SaveChanges();

            return RedirectToAction("Index");
        }

        /// <summary>
        /// 删除成员Get请求
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns></returns>
        [Authentication]
        public ActionResult Delete(int id)
        {
            //获得所有可用的账户信息
            var members = from m in _dbContext.Admins
                          where m.State != 0
                          select m;

            //如果是最后一个管理员，则不允许删除
            if (members.Count() <= 1)
            {
                TempData.Add("PageMessage", "此用户无法删除，必须保证存在至少一个管理员");
                return RedirectToAction("Index");
            }

            CurrentUserInfo currentUserInfo = SecurityHelper.GetCurrentUserInfo();

            //将管理员的状态设置为已删除
            var member = members.FirstOrDefault(m => m.AdminID == id);

            if (member.AdminID == currentUserInfo.UserId)
            {
                TempData.Add("PageMessage", "用户本人不能删除自己的帐号！");
                return RedirectToAction("Index");
            }
            member.State = 0;

            _dbContext.SaveChanges();

            return RedirectToAction("Index");
        }
    }
}
